#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <openssl/md5.h>

#define PORT 8080
#define BUFFER_SIZE 4096
#define MD5_DIGEST_LENGTH 16

// 反序列化字符串
int deserialize_string(const uint8_t* buffer, char* str, size_t str_size) {
    uint32_t net_len;
    memcpy(&net_len, buffer, sizeof(net_len));
    size_t len = ntohl(net_len);
    
    if (len >= str_size) {
        return -1; // 字符串缓冲区太小
    }
    
    memcpy(str, buffer + sizeof(net_len), len);
    str[len] = '\0';
    
    return sizeof(net_len) + len;
}

// 计算文件的MD5
int calculate_file_md5(const char* filename, uint8_t* md5_digest) {
    FILE* file = fopen(filename, "rb");
    if (!file) {
        return -1;
    }
    
    MD5_CTX md5_ctx;
    MD5_Init(&md5_ctx);
    
    uint8_t buffer[BUFFER_SIZE];
    size_t bytes_read;
    
    while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
        MD5_Update(&md5_ctx, buffer, bytes_read);
    }
    
    MD5_Final(md5_digest, &md5_ctx);
    
    fclose(file);
    return 0;
}

// 处理客户端请求
void handle_client(int client_sock) {
    uint8_t buffer[BUFFER_SIZE];
    int bytes_read = recv(client_sock, buffer, BUFFER_SIZE, 0);
    
    if (bytes_read <= 0) {
        perror("接收请求失败");
        return;
    }
    
    char filename[256];
    int offset = deserialize_string(buffer, filename, sizeof(filename));
    
    if (offset < 0) {
        printf("文件名反序列化失败\n");
        return;
    }
    
    printf("收到文件请求: %s\n", filename);
    
    // 检查文件是否存在
    struct stat st;
    if (stat(filename, &st) != 0) {
        printf("文件不存在: %s\n", filename);
        // 发送错误响应（这里简化处理，直接关闭连接）
        return;
    }
    
    // 计算文件的MD5
    uint8_t md5_digest[MD5_DIGEST_LENGTH];
    if (calculate_file_md5(filename, md5_digest) != 0) {
        printf("计算MD5失败: %s\n", filename);
        return;
    }
    
    // 发送文件信息
    uint8_t response[BUFFER_SIZE];
    int response_offset = 0;
    
    // 序列化文件名
    uint32_t net_filename_len = htonl(strlen(filename));
    memcpy(response + response_offset, &net_filename_len, sizeof(net_filename_len));
    response_offset += sizeof(net_filename_len);
    
    memcpy(response + response_offset, filename, strlen(filename));
    response_offset += strlen(filename);
    
    // 发送文件大小（大端序）
    uint64_t net_file_size = htobe64(st.st_size);
    memcpy(response + response_offset, &net_file_size, sizeof(net_file_size));
    response_offset += sizeof(net_file_size);
    
    // 发送MD5摘要
    memcpy(response + response_offset, md5_digest, MD5_DIGEST_LENGTH);
    response_offset += MD5_DIGEST_LENGTH;
    
    // 发送文件信息
    if (send(client_sock, response, response_offset, 0) < 0) {
        perror("发送文件信息失败");
        return;
    }
    
    printf("发送文件信息: %s (%ld bytes)\n", filename, st.st_size);
    
    // 发送文件内容
    FILE* file = fopen(filename, "rb");
    if (!file) {
        perror("打开文件失败");
        return;
    }
    
    size_t bytes_sent_total = 0;
    while (!feof(file)) {
        size_t bytes_read = fread(buffer, 1, BUFFER_SIZE, file);
        if (bytes_read > 0) {
            if (send(client_sock, buffer, bytes_read, 0) < 0) {
                perror("发送文件内容失败");
                break;
            }
            bytes_sent_total += bytes_read;
            
            // 显示进度
            int progress = (int)((double)bytes_sent_total / st.st_size * 100);
            printf("\r发送进度: %d%%", progress);
            fflush(stdout);
        }
    }
    
    printf("\n文件发送完成: %s\n", filename);
    fclose(file);
}

int main() {
    int server_fd, client_sock;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    // 绑定套接字
    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    // 监听
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    
    printf("文件服务器启动，监听端口 %d\n", PORT);
    
    while (1) {
        // 接受连接
        if ((client_sock = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            continue;
        }
        
        printf("客户端连接成功\n");
        
        // 处理客户端请求
        handle_client(client_sock);
        
        close(client_sock);
        printf("客户端连接关闭\n");
    }
    
    return 0;
}